package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    // 根据用户角色获取菜单信息
    @Override
    public List<Menu> getMenuList(String username) {

        List<Menu> menuList = menuDao.getMenuList(username);

        return menuList;

    }




    //分页查询
    @Override
    public PageResult findpage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        List<Menu> list = menuDao.findPage(queryString);
        PageInfo pageInfo = new PageInfo(list);
        long total = pageInfo.getTotal();
        List pageInfoList = pageInfo.getList();
        return new PageResult(total, pageInfoList);
    }



    //添加
    @Override
    public void add(Menu menu) {
        menuDao.add(menu);
    }


    //按Id查询回显
    @Override
    public Menu findById(Integer id) {
        Menu menu=menuDao.findById(id);
        return menu;
    }


    //修改
    @Override
    public void update(Menu menu) {
        menuDao.update(menu);
    }



    //删除
    @Override
    public void delete(Integer id) {
        Menu menu = menuDao.findById(id);
        Integer parentMenuId = menu.getParentMenuId();
        Integer count=menuDao.findSonCountById(id);

        if (parentMenuId!=null || count==0){
            menuDao.delete(id);
        }else {
            throw new RuntimeException(MessageConstant.DELETE_Menu_FAIL);
        }
    }


    //根据level(父子标识)查询菜单
    @Override
    public List<Menu> findAll(Integer level) {
        List<Menu> list=menuDao.findAll(level);
        return list;
    }


    //根据id查询菜单级别level
    @Override
    public Integer findLevelById(Integer id) {
        Integer parentId = menuDao.findLevelById(id);
        System.out.println(parentId);
        return parentId;
    }

}
